package com.hwz.hwzliving.commodity.exception;

import com.hwz.common.exception.HwzlivingCodeException;
import com.hwz.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ResponseBody
@Slf4j
@ControllerAdvice(basePackages = "com.hwz.hwzliving.commodity.controller")
public class HwzlivingExceptionControllerAdvice {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R HandleValidateException(MethodArgumentNotValidException e){
        log.error(e.getMessage());
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach(fieldError -> {
            //将错误字段名称和错误返回信息放入map
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(HwzlivingCodeException.INVALIDATE_EXCEPTION.getCode(),
                HwzlivingCodeException.INVALIDATE_EXCEPTION.getMsg()).put("data", map);
    }


    @ExceptionHandler({Throwable.class})
    public R HandleException(Throwable throwable){

        return R.error(HwzlivingCodeException.UNKNOWN_EXCEPTION.getCode(), HwzlivingCodeException.UNKNOWN_EXCEPTION.getMsg());
    }
}
